using UnityEngine.Rendering;
using System.Collections.Generic;
using UnityEngine;

public class MyRenderer : MonoBehaviour
{
    #region Variables
    public HiZBuffer m_hizBuffer;
    public ComputeShader CullingShader;

    public Camera mainCamera;


    private int kernelID_frustumCull;
    private int WORKER_THREAD = 256;
    private uint instanceCount = 10000;
    private List<uint> isVisibleBuffer_CPU;
    private List<InstanceBound> worldBBoxBuffer_CPU;
    private ComputeBuffer worldBBoxBuffer;
    private ComputeBuffer isVisibleBuffer;

    private int id_MAT_PV = Shader.PropertyToID("MAT_PV");
    private int id_instanceCount = Shader.PropertyToID("instanceCount");
    private int id_worldBBoxBuffer = Shader.PropertyToID("worldBBoxBuffer");
    private int id_isVisibleBuffer = Shader.PropertyToID("isVisibleBuffer");
    private bool m_initialized = false;
    #endregion

    private void Awake()
    {
        m_hizBuffer.InitializeHiZBuffer();
        kernelID_frustumCull = CullingShader.FindKernel("frustumCull");
        isVisibleBuffer_CPU = new List<uint>();
        worldBBoxBuffer_CPU = new List<InstanceBound>();
    }
    private void OnPreCull()
    {
        if (!m_initialized)
            return;
        Matrix4x4 mat_pv = mainCamera.projectionMatrix * mainCamera.cameraToWorldMatrix;
        CullingShader.SetMatrix(id_MAT_PV, mat_pv);
        CullingShader.SetInt(id_instanceCount, (int)instanceCount);

        CullingShader.SetBuffer(kernelID_frustumCull, id_isVisibleBuffer, isVisibleBuffer);
        CullingShader.SetBuffer(kernelID_frustumCull, id_worldBBoxBuffer, worldBBoxBuffer);
        CullingShader.Dispatch(kernelID_frustumCull, (int)instanceCount / WORKER_THREAD + 1, 1, 1);

    }

    /*
    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        RenderTexture depth = m_hizBuffer.Texture;
        //Graphics.SetRenderTarget(de)
        GL.Clear(true, true, Color.black);
        //Graphics.Blit(depth, destination);
    }
    */
    private void OnDisable()
    {
        isVisibleBuffer_CPU = null;
        worldBBoxBuffer_CPU = null;
    }
}
